<template>
  <a-form
    ref="ruleForm"
    :model="ruleForm"
    :rules="rules"
    v-bind="layout"
    @finish="handleFinish"
  >
    <a-form-item has-feedback label="用户名" name="username">
      <a-input v-model:value="ruleForm.username" />
    </a-form-item>
    <a-form-item label="性别" name="gender">
      <a-radio-group v-model:value="ruleForm.gender">
        <a-radio value="0"> 男 </a-radio>
        <a-radio value="1"> 女 </a-radio>
      </a-radio-group>
    </a-form-item>
    <a-form-item has-feedback label="密码" name="password">
      <a-input
        v-model:value="ruleForm.password"
        type="password"
        autocomplete="off"
      />
    </a-form-item>
    <a-form-item has-feedback label="确认密码" name="checkPassword">
      <a-input
        v-model:value="ruleForm.checkPassword"
        type="password"
        autocomplete="off"
      />
    </a-form-item>
    <a-form-item label="用户组" name="group">
      <a-transfer
        :data-source="groups"
        :titles="['可用用户组', '选中的用户组']"
        :target-keys="targetGroupKeys"
        :selected-keys="selectedGroupKeys"
        :render="(item) => item.title"
        @change="handleChange"
        @selectChange="handleSelectChange"
        :locale="{
          itemUnit: '项',
          itemsUnit: '项',
          notFoundContent: '列表为空',
          searchPlaceholder: '请输入搜索内容',
        }"
      />
    </a-form-item>
    <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
      <a-button type="primary" :loading="submitting" html-type="submit">
        {{ submitting ? "提交中" : "确定" }}
      </a-button>
    </a-form-item>
  </a-form>
</template>
<script>
import { message } from "ant-design-vue";

export default {
  name: "AddOrEditUser",
  // url !== ''则为编辑操作，否则为添加
  props: ["url"],
  emits: ["operate-success", "operate-failed"],
  data() {
    // validStr不包含空格
    let isValidStr = (str) => {
      return str.indexOf(" ") === -1;
    };
    let validateUsername = async (rule, value) => {
      if (value === "") {
        return Promise.reject("请输入用户名");
      } else {
        if (!isValidStr(value)) {
          return Promise.reject("用户名含有非法字符");
        }
        if (this.ruleForm.password !== "") {
          this.$refs.ruleForm.validateField("password");
        }
        return Promise.resolve();
      }
    };
    let validatePassword = async (rule, value) => {
      if (value === "") {
        return Promise.reject("请输入密码");
      } else {
        if (!isValidStr(value)) {
          return Promise.reject("密码含有非法字符");
        }
        if (this.ruleForm.checkPassword !== "") {
          this.$refs.ruleForm.validateField("checkPassword");
        }
        return Promise.resolve();
      }
    };
    let validateCheckPassword = async (rule, value) => {
      if (value === "") {
        return Promise.reject("请再次输入密码");
      } else if (!isValidStr(value)) {
        return Promise.reject("密码含有非法字符");
      } else if (value !== this.ruleForm.password) {
        return Promise.reject("输入不一致");
      } else {
        return Promise.resolve();
      }
    };
    return {
      submitting: false,
      ruleForm: {
        username: "",
        password: "",
        checkPassword: "",
        gender: "0",
      },
      rules: {
        username: [
          {
            validator: validateUsername,
            trigger: "change",
            required: true,
            whitespace: true,
          },
        ],
        password: [
          {
            validator: validatePassword,
            trigger: "change",
            required: true,
            whitespace: true,
          },
        ],
        checkPassword: [
          {
            validator: validateCheckPassword,
            trigger: "change",
            required: true,
            whitespace: true,
          },
        ],
        gender: [
          {
            required: true,
          },
        ],
      },
      layout: {
        labelCol: { span: 4 },
        wrapperCol: { span: 14 },
      },
      groups: [],
      targetGroupKeys: [],
      selectedGroupKeys: [],
    };
  },
  mounted() {
    this.fetch();
  },
  methods: {
    fetch() {
      this.axios
        .get("/user_management/groups/")
        .then((res) => {
          const data = res.data;
          for (let i = 0; i < data.length; i++) {
            this.groups.push({
              key: data[i].url,
              title: data[i].name,
            });
          }
          if (this.url !== "") {
            this.axios
              .get(this.url)
              .then((res) => {
                const data = res.data;
                this.ruleForm.username = data.username;
                this.ruleForm.gender = data.gender;
                this.ruleForm.password = this.ruleForm.checkPassword =
                  data.password;
                this.targetGroupKeys = data.groups;
              })
              .catch((error) => {
                console.log("Error", error.message);
              });
          }
        })
        .catch((error) => {
          console.log("Error", error.message);
        });
    },
    handleFinish(values) {
      this.submitting = true;
      const formData = new FormData();
      formData.append("username", values.username);
      formData.append("gender", values.gender);
      formData.append("password", values.password);
      this.targetGroupKeys.forEach((permission) => {
        formData.append("groups", permission);
      });
      // console.log("values:", values);
      if (this.url !== "") {
        this.axios
          .put(this.url, formData)
          .then(() => {
            this.submitting = false;
            message.success("修改成功！");
            this.$emit("operate-success");
          })
          .catch((error) => {
            this.submitting = false;
            message.error("修改失败！");
            this.$emit("operate-failed");
            console.log("Error", error.message);
          });
      } else {
        this.axios
          .post("/user_management/users/", formData)
          .then(() => {
            this.submitting = false;
            message.success("添加成功！");
            this.$emit("operate-success");
          })
          .catch((error) => {
            this.submitting = false;
            message.error("添加失败！");
            this.$emit("operate-failed");
            console.log("Error", error.message);
          });
      }
    },
    // handleFinishFailed(errors) {
    //   console.log(errors);
    // },
    handleChange(nextTargetKeys) {
      this.targetGroupKeys = nextTargetKeys
    },
    handleSelectChange(sourceSelectedKeys, targetSelectedKeys) {
      this.selectedGroupKeys = [
        ...sourceSelectedKeys,
        ...targetSelectedKeys,
      ]
      // console.log('sourceSelectedKeys: ', sourceSelectedKeys)
      // console.log('targetSelectedKeys: ', targetSelectedKeys)
    },
  },
};
</script>
